<script setup>
import { ref, onMounted } from 'vue'
import { getIpApi } from '@/api/ip'
const message = ref()
const reciveMessage = ref()
const Ip = ref({
  localIp: "192.168.100.1",
  targetIp: null
})
let websocket = null
const socketMessage = ref('') // 通信记录（持久保存）
const messageHistory = ref([]) // 消息历史记录
const judge = () => {
  if ('WebSocket' in window) {
    websocket = new WebSocket("ws://" + Ip.value.localIp + ":8080/ws/" + Ip.value.targetIp); //连接WebSocket节点
    // console.log("ws://" + Ip.value.localIp + ":8080/ws/")
    // websocket = new WebSocket("ws://192.168.100.1:8080/ws/" + Ip.value.targetIp); //连接WebSocket节点
  } else {
    alert('Not support websocket')
  }
  //连接发生错误的回调方法
  websocket.onerror = function () {
    console.error('WebSocket连接错误:', error);
    setMessageInnerHTML("error");
  };

  //连接成功建立的回调方法
  websocket.onopen = function () {
    console.log('WebSocket连接成功!', event);
    setMessageInnerHTML("连接成功");
  }

  //接收到消息的回调方法
  websocket.onmessage = function (event) {
    console.log('收到消息:', event.data)
    setMessageInnerHTML(event.data);
    reciveMessage.value = event.data
  }

  //连接关闭的回调方法
  websocket.onclose = function () {
    setMessageInnerHTML("close");
  }

  //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
  window.onbeforeunload = function () {
    websocket.close();
  }
}
const getIp = async () => {
  let res = await getIpApi()
  Ip.value.localIp = res.ip
}
// 将消息显示在网页上
function setMessageInnerHTML(innerHTML) {
  socketMessage.value += innerHTML + '\n'
  messageHistory.value.push({
    type: 'system',
    content: innerHTML,
    timestamp: new Date()
  })
}
// 发送消息
function send() {
  if (websocket && websocket.readyState === WebSocket.OPEN) {
    const messageData = {
      // targetIp: Ip.value.targetIp,
      message: message.value,
      sourceIp: Ip.value.localIp
    }

    websocket.send(JSON.stringify(messageData))
    // setMessageInnerHTML(`发送到 ${Ip.value.targetIp}: ${message.value}`)
    // 保存到消息历史
    const sendRecord = `发送到 ${Ip.value.targetIp}: ${message.value}`
    setMessageInnerHTML(sendRecord)
    messageHistory.value.push({
      type: 'sent',
      content: message.value,
      target: Ip.value.targetIp,
      timestamp: new Date()
    })
    message.value = '' // 清空输入框
  } else {
    alert('WebSocket连接未建立')
  }
}
// 关闭连接
function closeWebSocket() {
  if (websocket) {
    websocket.close()
  }
}
onMounted(async () => {
  getIp()
  judge()
})
</script>
<template>
  这个是通信用的
  <el-form :inline="true" :model="Ip">
    <el-form-item label="本机ip">
      <el-input v-model="Ip.localIp" disabled />
    </el-form-item>
    <el-form-item label="连接至">
      <el-input v-model="Ip.targetIp" />
    </el-form-item>
  </el-form>
  <el-form :model="message">
    <el-form-item>
      <el-button type="primary" @click="send">发送</el-button>
      <el-button @click="closeWebSocket">断开连接</el-button>
    </el-form-item>
    <el-form-item label="发送信息" style="width: 600px;">
      <el-input v-model="message" type="textarea" />
    </el-form-item>
    <!-- <el-form-item label="收到的信息" style="width: 600px;">
      <el-input v-model="reciveMessage" type="textarea" readonly />
    </el-form-item> -->
    <el-form-item label="通信记录" style="width: 600px;">
      <el-input type="textarea" :value="socketMessage" :rows="10" readonly />
    </el-form-item>
  </el-form>
</template>